import axiosStatic, { InternalAxiosRequestConfig, type AxiosError, type AxiosResponse } from 'axios';
import type { App } from 'vue';
import { httpSettings } from '@/settings/http';
import router from '@/plugins/router';

const axios = axiosStatic.create({
  baseURL: httpSettings.prefix,
  timeout: httpSettings.timeout,
});

const getErrorMessage = (error: AxiosError<unknown>) => {
  const response = error.response;
  if (response && response.data) {
    return (response.data as { errorMessage: string }).errorMessage || '';
  }
  return '';
};

// 获取 HTTP 请求头
export const getHTTPHeaders = (): Record<string, string> => {
  const newHeaders: Record<string, string> = {};
  const routeName = router.currentRoute.value.name;
  if (routeName) {
    newHeaders.Ui = String(routeName);
  }
  newHeaders['Env-App'] = import.meta.env.VITE_ENV_APP;
  return newHeaders;
};

axios.interceptors.request.use(
  (cfg: InternalAxiosRequestConfig) => {
    cfg.headers = Object.assign(cfg.headers || {}, getHTTPHeaders());
    return cfg;
  },
  (err: unknown) => {
    console.error(err);
    return Promise.reject(new Error('客户端配置错误!'));
  },
);

axios.interceptors.response.use(
  (response: AxiosResponse) => {
    // 下载文件
    const contentType = response.headers['content-type'];
    if (contentType && contentType.indexOf('application/vnd.ms-excel') > -1) {
      let fileName = '';
      const descriptions: Array<string> = (response.headers['content-disposition'] || '').split(';');
      for (let i = 0; i < descriptions.length; i++) {
        const keyValue = descriptions[i].split('=');
        if (keyValue.length > 1 && keyValue[0] == 'filename') {
          fileName = keyValue[1];
          break;
        }
      }
      // 下载文件
      return Promise.resolve({
        ext: { fileName },
        data: response.data,
      });
    }
    return Promise.resolve(response.data);
  },
  (error: AxiosError<unknown>) => {
    const response = error.response;
    const status = response ? Number(response.status) : -1;
    const location_ = response?.headers?.location;
    switch (status) {
      case 401:
        // AJAX 通过 401 发起登录重定向，因为 AJAX 无法正确处理 302 重定向
        if (location_) {
          window.location.href = location_;
          // 不弹错误提示，也不进入成功回调
          return Promise.reject('');
        }
        return Promise.reject('请重新登陆');
      case 500:
        return Promise.reject('服务忙，请稍后再试');
      default:
        return Promise.reject(getErrorMessage(error));
    }
  },
);

export { axios };

export default {
  install: (app: App) => {
    app.config.globalProperties.$axios = axios;
  },
};
